#include "cgzCLua.h"
#include "cgzCTcpGateC.h"
#include "cgzCThreadPool.h"

bool cgzCLua::rungc(const cgzITask *iTask, cgzCLoopC *pnode)
{
    auto etype = pnode->getEType();
    switch (etype)
    {
    case TCPC_ACPT: // 连接成功
    {
        ocall(iTask->m_tref, "accept", {});
    }
    break;
    case TCPC_DISC: // 断开连接
    {
        ocall(iTask->m_tref, "disc", {});
    }
    break;
    default:
    {
        cgz_this_error("{} type:{} not support", iTask->getName(), (int)etype);
    }
    }
    return true;
}

static int link(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    const char *ip = lua_tostring(L, 2);
    int port = lua_tointeger(L, 3);
    int tref = luaL_ref(L, LUA_REGISTRYINDEX);
    void *node = malloc(sizeof(cgzCTcpGateC));
    int cid = that->getId();
    auto ctcp = new (node) cgzCTcpGateC(that->m_pool, name, ip, port, cid);
    ctcp->m_tref = tref;
    ctcp->tcpinit();
    lua_pushinteger(L,ctcp->getId());
    return 1;
}


static int forward_add(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    void *node = malloc(sizeof(cgzCGAddC));
    auto pCmd = new (node) cgzCGAddC();
    lua_pushnil(L);
    while(lua_next(L,-2))
    {
        int mid = lua_tointeger(L,-2);
        int tid = lua_tointeger(L,-1);
        pCmd->map[mid] = tid;
        lua_pop(L,1);
    }
    that->regTask(name, pCmd);
    return 0;
}

static int forward_del(lua_State *L)
{
   // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    void *node = malloc(sizeof(cgzCGDelC));
    auto pCmd = new (node) cgzCGDelC();
    lua_pushnil(L);
    while(lua_next(L,-2))
    {
        int mid = lua_tointeger(L,-2);
        pCmd->set.insert(mid);
        lua_pop(L,1);
    }
    that->regTask(name, pCmd);
    return 0;
}

static int forward_cls(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    void *node = malloc(sizeof(cgzCGClrC));
    auto pCmd = new (node) cgzCGClrC();
    that->regTask(name, pCmd);
    return 0;
}


int cgzCLua::luaopen_tcpGateC(lua_State *L)
{
    static const luaL_Reg otherlib[] = {
        {"link", link},
        {"forward_add", forward_add},
        {"forward_del", forward_del},
        {"forward_cls", forward_cls},
        {NULL, NULL},
    };
    luaL_newlib(L, otherlib);
    return 1;
}